<template>
  <div class="field" @click="showPicker = true">
    <div class="text">{{ initText }}</div>
    <div class="error"></div>
    <div class="icon iconfont icon-jiantou"></div>
  </div>

  <van-popup v-model:show="showPicker" round :position="position">
    <van-picker :columns="list" @cancel="showPicker = false" @confirm="onConfirm" />
  </van-popup>
</template>

<script setup>
import { dicts, getDicts } from '@/store/dict.js';
import { ref, onMounted, watch } from 'vue';

const props = defineProps({
  placeholder: '请选择',
  value: { type: String, default: '' },
  propText: { type: String, default: 'text' }, //  需要返回的字段
  propValue: { type: String, default: 'value' }, // 需要返回的值
  position: { type: String, default: 'bottom' },
  dictName: { type: String, default: '' },
  dataList: { type: String, default: () => ([]) }
})

const emit = defineEmits(['update:value', 'change']);

const list = ref([]);
const initText = ref('');
const initValue = ref(props.value || ''); //  记录初始化的值，同时这个值也是具有响应式的

watch(() => dicts.value[props.dictName], (newVal, oldVal) => {
  if (newVal && newVal.length > 0) {
    setResult(newVal);
  }
})


fetctDataList();
async function fetctDataList() {
  list.value = [];  //  减少缓存造成的不必要的麻烦

  if (props.dataList && props.dataList.length > 0) {
    setResult(props.dataList);
  } else {
    await getDicts([props.dictName])
  }
}


function setResult(data) {
  const _data = JSON.parse(JSON.stringify(data));

  list.value = _data.map(_s => {
    _s.text = _s[props.propText];
    _s.value = _s[props.propValue];
    return _s;
  });

  init(list.value); //  初始化数据
}

//  用于第一次初始化数据
async function init(data) {
  const _data = data.find(_s => _s.value === props.value);

  if (!_data) return;
  initText.value = _data?.text;
  initValue.value = _data?.value;
}

async function setInit(data = []) {
  const _data = data[0];
  initText.value = _data?.text;
  initValue.value = _data?.value;
}

//  控制弹窗的展示
const showPicker = ref(false);

const onConfirm = ({ selectedOptions }) => {
  setInit(selectedOptions);
  emit('update:value', selectedOptions[0].value);
  emit('change', selectedOptions[0].value);

  showPicker.value = false;  // 关闭弹窗
}
</script>

<style lang="scss" scoped>
:deep .van-picker {
  max-height: 60vh;

  .van-picker__toolbar {
    height: 5rem;

    button {
      font-size: 1.6rem;
    }
  }
}

//  去除默认样式， 更好的自定义样式  
.field {
  display: flex;
  align-items: center;
  padding: 2rem 0;

  .text {
    flex: 1;
  }

  .icon {}
}
</style>